package com.jews.common.model;

import com.jews.common.constants.BaseEnum;
import com.jews.common.constants.CodeEnum;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Setter;

import java.util.Objects;

/**
 * 响应JSON对象
 *
 * @author JewsChen
 * @title: JsonObject
 * @date 2022/11/29 22:43
 */
@Data
public class JsonObject<E> {
    /**
     * 日志id
     */
    private String logId;

    /**
     * 响应状态
     */
    @Setter(AccessLevel.PRIVATE)
    private Integer status;

    /**
     * 响应描述
     */
    @Setter(AccessLevel.PRIVATE)
    private String msg;

    /**
     * 响应数据
     */
    @Setter(AccessLevel.PRIVATE)
    private E data;

    /**
     * 服务器当前时间
     */
    @Setter(AccessLevel.PRIVATE)
    private Long serverTime;

    /**
     * traceId
     */
    @Setter(AccessLevel.PRIVATE)
    private String ticket;

    /**
     * API版本
     */
    @Setter(AccessLevel.PRIVATE)
    private String apiVersion;

    private JsonObject() {
        serverTime = System.currentTimeMillis();
        logId = "123";
        ticket = "456";
        apiVersion = "v1";
    }

    public JsonObject(Integer status, String msg) {
        this();
        this.status = status;
        this.msg = msg;
    }

    private JsonObject(Integer status, String msg, E data) {
        this();
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public static JsonObject success() {
        return res(CodeEnum.Success);
    }

//    public static JsonObject retSuccess(String msg) {
//        return new JsonObject(CodeEnum.Success.getCode(), msg);
//    }

    public static <E> JsonObject<E> success(E data) {
        return res(CodeEnum.Success, data);
    }

    public static <E> JsonObject<E> retSuccess(String msg, E data) {
        return new JsonObject<>(CodeEnum.Success.getCode(), msg, data);
    }

    public static JsonObject fail() {
        return res(CodeEnum.Fail);
    }

    public static JsonObject fail(String msg) {
        return new JsonObject(CodeEnum.Fail.getCode(), msg);
    }

    public static JsonObject res(BaseEnum<CodeEnum> codeEnum) {
        return new JsonObject(codeEnum.getCode(), codeEnum.getName());
    }

    public static <E> JsonObject<E> res(BaseEnum codeEnum, E data) {
        return new JsonObject<>(codeEnum.getCode(), codeEnum.getName(), data);
    }

    /**
     * 是否成功
     *
     * @return true=成功,false=失败
     */
    public boolean isOk() {
        return Objects.equals(CodeEnum.Success.getCode(), this.status);
    }
}
